<?php

namespace App\Models\Account;

use App\Models\BaseModel;
use App\Helpers\Code;

class UserPermissionCategory extends BaseModel
{

    protected $table = 'user_permission_categories';
    protected $visible = ['id', 'title', 'permissions', 'description', 'created_at', 'updated_at'];
    protected $fillable = ['title', 'description', 'data_scope'];
    public $params = ['title'];
    public $sorters = ['title', 'created_at'];

    public function permissions()
    {
        return $this->hasMany('App\Models\Account\UserPermission', 'group_id');
    }

    public function addCategory($data)
    {
        $data['data_scope'] = $this->getDataScope();
        return $this->create($data);
    }

    public function deleteCategory($id)
    {
        $model = $this->with('permissions')->find($id);

        if (!$model) {
            return null;
        } else if ($model->permissions->count() > 0) {
            return Code::INSIDE_EXIST_DEPENDENCE;
        }

        return $model->delete();
    }

    public function editCategory($id, $data)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        return $model->updateOrCreate(['id' => $id], $data);
    }

    public function getCategoryList($limit, $sorter, $search)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        $model = $this->with(['permissions:id,group_id,title,slug,http_method,http_path,is_enabled,description'])->orderBy($sorter[0], $sorter[1]);
        $model->select(['id', 'title', 'description', 'created_at']);
        foreach ($search as $key => $value) {
            switch ($key) {
                case 'title':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }
        return $model->paginate($perPage)->toArray();
    }

    public function getPermissionListAll()
    {
        return $this->with(['permissions:id,title,slug,http_method,group_id'])
                        ->get(['id', 'title'])
                        ->toArray();

//        return $this->with(['permissions' => function($query) {
//                        $query->select('id', 'title', 'group_id');
//                    }])->get()->toArray();
    }

    public function getCategoryListAll()
    {
        return $this->all(['id', 'title'])->toArray();
    }

    public function getCategoryPermissionList($id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        return $model->permissions()->paginate($this->limit)->toArray();
    }

    public function getCategory($id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        return $model->toArray();
    }

}
